<template>
  <div class="container">
    <div class="app-container">
      <el-tree :default-expand-all="true" :data="data" :expand-on-click-node="false" :props="defaultProps">
        <template v-slot="{node,data}">
          <el-row type="flex" style="width: 100%;height: 40px;" justify="space-between" >
          <el-col style="line-height: 40px;">{{ data.name }}</el-col>
          <el-col :span="4">
            <span class="tree-manager">{{ data.managerName }}</span>
            <el-dropdown>
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item ><a href="" @click.prevent="add(data)">添加子部门</a></el-dropdown-item>
              <el-dropdown-item><a href="" @click.prevent="update(data)">编辑部门</a></el-dropdown-item>
              <el-dropdown-item ><a @click.prevent="deletes(data.id)">删除</a></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          </el-col>
        </el-row>
        </template>
      </el-tree>
      <Form :title="title" ref="form" :dialogTableVisible.sync="flag" :items="whichItem" @department="addPart"></Form>
    </div>
  </div>
</template>
<script>
import {getDepartmentList,deleteDepartment,getDepartmentDetail} from '@/api/department'
import {transListToTreeData} from '@/utils/index'
import Form from '@/components/Dialog/index.vue'
export default {
  name: 'Department',
  components:{
    Form
  },
  data() {
    return {
      data:[
      ],
      defaultProps:{ 
        label:'name',  // 显示字段的名字
        children:'children'  // 读取子节点的字段名
      },
      flag:false,
      title:'',
      whichItem:{}
    }
  },
  async created() {
    await this.init()
    // console.log(this.data);
  },
  methods:{
    // 初始化
    async init() {
      const result=await getDepartmentList()
      this.data=transListToTreeData(result,0)
    },
    // 添加子部门
    add(data) {
      this.title='新增部门'
      this.flag=true
      this.whichItem=data
    },
    // 修改部门
    async update(data) {
      this.title='编辑部门'
      this.flag=true
      const result=await getDepartmentDetail(data.id)
      this.whichItem=result
    },
    async addPart() {
      await this.init()
    },
    // 删除
    deletes(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await deleteDepartment(id)
          await this.init()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px 35px;

}
</style>
